package phone.qyg.com.qyg.activity;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.app.adapter.recycler.CommonAdapter;
import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.RecyclerViewItemDecoration;
import com.app.adapter.recycler.base.ViewHolder;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.SharePrefUtil;
import com.app.utils.TransformController;
import com.app.vhtable.VHTableAdapter;
import com.app.vhtable.vhtableview.VHTableView;
import com.cocosw.bottomsheet.BottomSheet;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.FieldPlace;
import phone.qyg.com.qyg.model.FieldPrice;
import phone.qyg.com.qyg.model.Order;
import phone.qyg.com.qyg.model.VenueActRoom;
import phone.qyg.com.qyg.utils.AppHttpRequest;

/**
 * 作者：lblbh on 2018/6/1 11:51
 * 邮箱：lanbuhan@163.com
 * 功能：场馆预定
 */
@ContentView(R.layout.venue_field)
public class VenueFieldActivity extends BaseActivity {

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.head_recycler)
    RecyclerView head_recycler;

    @ViewInject(R.id.select_recycler)
    RecyclerView select_recycler;

    @ViewInject(R.id.vht_table)
    VHTableView vht_table;

    @ViewInject(R.id.bottom_rela)
    RelativeLayout bottom_rela;

    @ViewInject(R.id.rela_order)
    RelativeLayout rela_order;

    @ViewInject(R.id.bottom_linear)
    LinearLayout bottom_linear;

    @ViewInject(R.id.submit_order)
    TextView submit_order;

    CommonAdapter adapterTempField;

    List<FieldPrice> selectPrices;

    String title;

    int roomId;

    int venueId;

    @Override
    public void initSucessView() {

        Object obj = getTransModels();

        if(obj instanceof VenueActRoom){
            VenueActRoom room = (VenueActRoom) obj;
            roomId = room.id;
            venueId = room.venueId;
            title = room.venueTitle;
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {

        mapKeys.put(AppHttpKey.ROOM_ID,String.valueOf(roomId));
        mapKeys.put(AppHttpKey.VENUE_ID,String.valueOf(venueId));
        AppHttpRequest.httpRequestDefalut(ApplicationConfig.VENUE_INFO_ORDER, mapKeys, new AppHttpRequest.OnAppHttpListener() {
            @Override
            public void onAppHttpState(boolean isState, String result) {
                if(isState){
                    List<VenueActRoom> models = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.VENUE_ACT_ROOM, VenueActRoom.class);
                    setHeadWeeks(models);
                }
            }
        });

        back.setText(setAttributeText(title));
    }

    @Event(value = {R.id.back,R.id.submit_order})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.submit_order:
                if(!isRequestStr(SharePrefUtil.getString(SharePrefUtil.KEY.APP_USER, ""))){
                    TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
                    return;
                }
                sumitInfo();
                break;
        }
    }

    /**
     * 提交订单信息
     */
    private void sumitInfo(){
        if(!isRequestList(selectPrices))
            return;
        mapKeys.put(AppHttpKey.ROOM_ID_TWO,String.valueOf(roomId));//活动室ID
        mapKeys.put(AppHttpKey.VENUE_ID,String.valueOf(venueId));//场馆ID
//
        List times = new ArrayList();
        final List<FieldPrice> infos = new ArrayList<FieldPrice>();
        for (int i=0,j=selectPrices.size();i<j;i++){
            FieldPrice fieldPrice = selectPrices.get(i);
//            fieldPrice.book_time = new StringBuffer(fieldPrice.book_time).append(" 00:00:00").toString();
            int timeId = fieldPrice.time_id;
            times.add(timeId);
            infos.add(fieldPrice);
        }
//
        mapKeys.put(AppHttpKey.TIME_IDS, CommonUtil.listToString(times,','));//预订时间段ID
        String dataValue = JSON.toJSONString(infos);
        mapKeys.put(AppHttpKey.DATA,dataValue);
        AppHttpRequest.httpPostRequestDefalut(ApplicationConfig.SUB_VENUERE_SERVAT,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(JSONTool.isStatus(result)){
                            Order order = JSONTool.jsonDefaluTranClazz(result,null,Order.class);
                            TransformController.transformControllerModel(QXApplication.getContext(),VenueOrderSucessActivity.class,order);
                        }else{
                            BottomSheet.Builder builder = new BottomSheet
                                    .Builder(VenueFieldActivity.this, com.cocosw.bottomsheet.R.style.BottomSheet_Dialog)
                                    .title("场地预定出现错误");
                            builder.sheet(0, JSONTool.errorHint(result));
//                            builder.sheet(1, "知道了");
//}
                            final BottomSheet sheet = builder.build();
//                            builder.listener(new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    if(which == 1){
//                                        sheet.dismiss();
//                                    }
//                                }
//                            });
                            sheet.show();
                        }
                    }
                });
    }

    private void setHeadWeeks(List<VenueActRoom> models){
        if(!isRequestList(models))
            return;
        //动态选中第一个
//        VenueDate temp = models.get(0);
//        temp.type = 1;
        for (int i=0,j=models.size();i<j;i++){
            VenueActRoom temp = models.get(i);
            if(temp.roomId == roomId){
                temp.type = 1;

                //执行场地请求
                setItemVenueData();
            }
        }

        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        head_recycler.addItemDecoration(new RecyclerViewItemDecoration(
                RecyclerViewItemDecoration.MODE_VERTICAL, getResources().getColor(R.color.no_color),5,0,0));
        head_recycler.setLayoutManager(layoutVerManager);
        final CommonAdapter adapter = new CommonAdapter<VenueActRoom>(QXApplication.getContext(),R.layout.venue_item_week,models) {
            @Override
            protected void convert(ViewHolder holder, VenueActRoom model, int position) {
                holder.setText(R.id.item_title,model.title);
                holder.setTextColorRes(R.id.item_title,(model.type == 1)?R.color.white:R.color.black);
                holder.setBackgroundRes(R.id.item_rela,(model.type == 1)?R.color.login_fill_btn:R.color.yes_reserce_solid);
            }
        };

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
//                System.out.println("我的大小是-->>>>"+position);
                if(position <0)
                    return;
                List<VenueActRoom> temps = adapter.getData();
                for (int i=0,j=temps.size();i<j;i++){
                    VenueActRoom temp = temps.get(i);
                    temp.type = (i == position) ? 1:0;
                }

                VenueActRoom room = temps.get(position);
                roomId = room.roomId;
                //更新放在获取下面执行
                adapter.notifyDataSetChanged();

                setItemVenueData();

                bottom_rela.setVisibility(View.VISIBLE);
                rela_order.setVisibility(View.GONE);
                bottom_linear.setVisibility(View.GONE);
                select_recycler.setVisibility(View.GONE);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        head_recycler.setAdapter(adapter);
    }

    /**
     * 根据head点击改变下面数据
     */
    private void setItemVenueData(){
        AppHttpRequest.getFieldMap(roomId,venueId,new AppHttpRequest.OnFieldMapListener(){
            @Override
            public void onFieldState(boolean isState, Map<String, Object> infoMap) {
                if(isState && !infoMap.isEmpty()){
                    ArrayList<FieldPlace> places = (ArrayList<FieldPlace>) infoMap.get(AppHttpRequest.FIELD_INFO_PLACE);
                    ArrayList<ArrayList<FieldPrice>> pricess = (ArrayList<ArrayList<FieldPrice>>) infoMap.get(AppHttpRequest.FIELD_INFO_PRICE);
                    if(isRequestList(places) && isRequestList(pricess)){
                        vht_table.setVisibility(View.VISIBLE);
                        VHTableAdapter tableAdapter=new VHTableAdapter(QXApplication.getContext(),places, pricess, new VHTableAdapter.OnVHTabletemOnClickUpdate() {
                            @Override
                            public void OnClickReserves(List<FieldPrice> prices) {

                                bottom_rela.setVisibility(isRequestList(prices) ? View.GONE:View.VISIBLE);
                                bottom_linear.setVisibility(isRequestList(prices) ? View.VISIBLE:View.GONE);
                                rela_order.setVisibility(isRequestList(prices) ? View.VISIBLE:View.GONE);
                                if(adapterTempField == null){
                                    setVenueTempField(prices);
                                }else{
                                    adapterTempField.notifyDataSetChanged();
                                }
                                selectPrices = prices;

                            }
                        });
                        vht_table.setAdapter(tableAdapter);

                    }else{
                        vht_table.setVisibility(View.GONE);
                    }
                }
            }
        });
    }




    private void setVenueTempField(List<FieldPrice> models){
//        LinearLayoutManager layoutVerManager = new_icon LinearLayoutManager(QXApplication.getContext());
        select_recycler.setVisibility((isRequestList(models))?View.VISIBLE:View.GONE);
        if(!isRequestList(models))return;
        CommonAdapter adapterTempField = new CommonAdapter<FieldPrice>(QXApplication.getContext(),R.layout.venue_field_item_temp,models) {
            @Override
            protected void convert(ViewHolder holder, FieldPrice model, int position) {
                holder.setText(R.id.user_name,model.start_time +"-"+ model.end_time);
                holder.setText(R.id.item_data,model.weekDate );//+" "+ model.price
            }
        };

        select_recycler.setAdapter(adapterTempField);
    }

    @Override
    public void initViewHandler() {
        GridLayoutManager girdLayoutManager = new GridLayoutManager(QXApplication.getContext(),4,GridLayoutManager.VERTICAL,false);
//        girdLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        select_recycler.addItemDecoration(new RecyclerViewItemDecoration(
                RecyclerViewItemDecoration.MODE_VERTICAL, getResources().getColor(R.color.no_color),5,0,0));
        select_recycler.setLayoutManager(girdLayoutManager);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initData(null);
        bottom_rela.setVisibility(View.VISIBLE);
        bottom_linear.setVisibility(View.GONE);
        rela_order.setVisibility(View.GONE);
        selectPrices = null;
    }
}
